package com.hanagent.controller;
  
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.hanagent.model.Admins;
import com.hanagent.model.Agentorders;
import com.hanagent.model.Agents;
import com.hanagent.model.Moneyrecords;
import com.hanagent.myModel.GoodStock;
import com.hanagent.utils.AgentStockUtils;
import com.hanagent.utils.ConstantUtils;
import com.hanagent.utils.MoneyUtils;
import com.hanagent.utils.ResponseUtils; 
import com.hanagent.utils.StrUtils;
import com.hanagent.utils.UUidUtils;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class AgentController extends Controller{

	public void getAgentInfo() { //代理商信息
		String agentId = getPara("agentId");
		Agents searchAgents = Agents.dao.findById(agentId);
		renderText(ResponseUtils.sendResult(1, searchAgents, "获取数据成功")); 
	}
	 
	public void getAgentStock() { //代理商库存
		Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
		
		String agentId = getPara("agentId");
		int loginAgentId = loginAgents.getAgentId();
		
		if (StrUtils.isEmpty(agentId) ) {
			agentId = loginAgentId+"";
		}else{ 
			Agents searchAgents = Agents.dao.findById(agentId);
			if (searchAgents==null) {
				renderText(ResponseUtils.sendResult(0, "", "找不到你要查找的代理商，请检查id"));
				return;
			}
			int parentAgentId = searchAgents.getAgentParentId();
			int secParentAgentId = searchAgents.getAgentSecondParentId();
			if (loginAgentId != searchAgents.getAgentId() && loginAgentId != parentAgentId && loginAgentId != secParentAgentId && loginAgents.getAgentLevel()!=ConstantUtils.LevelSuper) {
				renderText(ResponseUtils.sendResult(0, "", "你无权查看与你无关的代理商的库存"));
				return;
			}
		}
		
		//获取代理商库存
		ArrayList<Agentorders> listAgentBuyOrders = (ArrayList<Agentorders>) Agentorders.dao.find("select * from AgentOrders where buyAgentId = "
    			+ agentId + " and (state = " + ConstantUtils.StateOrderPass +
    			" or state = " + ConstantUtils.StateOrderSendGood + " or state = " + ConstantUtils.StateOrderTakeGood + ")");
    	ArrayList<GoodStock> goodBuyStocks = AgentStockUtils.statisticsOrderGood(listAgentBuyOrders);
      
    	ArrayList<Agentorders> listAgentSaleOrders = (ArrayList<Agentorders>) Agentorders.dao.find("select * from AgentOrders where saleAgentId = "
    			+ agentId  + " and (state = " + ConstantUtils.StateOrderPass +
    			" or state = " + ConstantUtils.StateOrderSendGood + " or state = " + ConstantUtils.StateOrderTakeGood + ")");
    	ArrayList<GoodStock> goodSaleStocks = AgentStockUtils.statisticsOrderGood(listAgentSaleOrders);
    	ArrayList<GoodStock> resultStocks = AgentStockUtils.calStock(goodBuyStocks, goodSaleStocks);
		renderText(ResponseUtils.sendResult(1, resultStocks, "获取数据成功")); 
	}
	
	public void getAgentAchievement() { //代理商业绩统计
		
		int pageNumber = getParaToInt("pageNumber")<1?1:getParaToInt("pageNumber");
		int pageSize = getParaToInt("pageSize")<1?1:getParaToInt("pageSize");
		String agentId = getPara("agentId");
		String startCreateTime = getPara("startCreateTime");
		if (StrUtils.isEmpty(startCreateTime)) {
			startCreateTime = "1917-12-05 16:00:00";
		} 
		String endCreateTime = getPara("endCreateTime");
		if (StrUtils.isEmpty(endCreateTime)) {
			endCreateTime = "3017-12-05 16:00:00";
		}  
		
		Agents searchAgents = Agents.dao.findById(agentId);
		if (searchAgents==null) {
			renderText(ResponseUtils.sendResult(0, "", "找不到你要查找的代理商，请检查id"));
			return;
		}
		
		//代理商业绩统计
		ArrayList<Agentorders> listAgentSaleOrders  = (ArrayList<Agentorders>) Agentorders.dao.find("select AgentOrders.*, Agents.agentName AS agentBuyName, "
				+ "AgentSale.agentName AS agentSaleName from AgentOrders INNER JOIN Agents ON AgentOrders.buyAgentId = Agents.agentId "
				+ "INNER JOIN Agents AgentSale ON AgentOrders.saleAgentId = AgentSale.agentId  "
				+ "where AgentOrders.createdAt > ? and  AgentOrders.createdAt < ? and (AgentOrders.state = " + ConstantUtils.StateOrderPass +
    			" or AgentOrders.state = " + ConstantUtils.StateOrderSendGood + " or AgentOrders.state = " + ConstantUtils.StateOrderTakeGood +
    			")  and (AgentOrders.agentSourceIds like '%"+ agentId +"%') order by AgentOrders.updatedAt desc", startCreateTime,  
				endCreateTime);
		
		//代理商业绩统计
		Page<Agentorders> list  = Agentorders.dao.paginate(pageNumber, pageSize, "select AgentOrders.*, Agents.agentName AS agentBuyName, "
						+ "AgentSale.agentName AS agentSaleName", " from AgentOrders INNER JOIN Agents ON AgentOrders.buyAgentId = Agents.agentId "
						+ "INNER JOIN Agents AgentSale ON AgentOrders.saleAgentId = AgentSale.agentId  "
						+ "where AgentOrders.createdAt > ? and  AgentOrders.createdAt < ? and (AgentOrders.state = " + ConstantUtils.StateOrderPass +
		    			" or AgentOrders.state = " + ConstantUtils.StateOrderSendGood + " or AgentOrders.state = " + ConstantUtils.StateOrderTakeGood +
		    			")  and (AgentOrders.agentSourceIds like '%"+ agentId +"%') order by AgentOrders.updatedAt desc", startCreateTime,  
						endCreateTime);
		
    	ArrayList<GoodStock> goodSaleStocks = AgentStockUtils.statisticsOrderGood(listAgentSaleOrders);
       
    	String dataInfo = "已售业绩统计：  ";
    	for (int i = 0; i < goodSaleStocks.size(); i++) {
    		GoodStock goodStock = goodSaleStocks.get(i);
			dataInfo = dataInfo + goodStock.name + ":" + goodStock.stock + "盒   ";
		}
    	
    	JSONObject dataJsonObject = new JSONObject();
    	dataJsonObject.put("achievementInfo", dataInfo);
    	dataJsonObject.put("orderList", list);
  
		renderText(ResponseUtils.sendResult(1, dataJsonObject, "获取数据成功")); 
	}
	
	public void shareNow(){
		Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
		if (loginAgents.getAgentLevel()!=ConstantUtils.LevelSuper) {
			renderText(ResponseUtils.sendResult(0, "", "只有公司管理员才可分红"));
			return;
		}
	 
		Record recordMax = Db.findFirst("select max(shareTime) as maxTime from AgentOrders");
		int maxTime = 0;
		if (recordMax.get("maxTime")!=null) {
			maxTime = recordMax.getInt("maxTime") + 1;
		}
		
		Record recordAgentOrderSum = Db.findFirst("select sum(price) as allPrice from AgentOrders where shareState = 0 and (state = " + ConstantUtils.StateOrderPass +
    			" or state = " + ConstantUtils.StateOrderSendGood + " or state = " + ConstantUtils.StateOrderTakeGood + ")");
		Record recordOrdersSum = Db.findFirst("select sum(price) as allPrice from Orders where shareState = 0 and (state = " + ConstantUtils.StateOrderPass +
    			" or state = " + ConstantUtils.StateOrderSendGood + " or state = " + ConstantUtils.StateOrderTakeGood + ")");
		double allPrice = 0; 
		if (recordAgentOrderSum.get("allPrice")!=null) {
			allPrice = allPrice + recordAgentOrderSum.getDouble("allPrice");
		}
		
		if (recordOrdersSum.get("allPrice")!=null) {
			allPrice = allPrice + recordOrdersSum.getDouble("allPrice");
		}

		if (allPrice==0) {
			renderText(ResponseUtils.sendResult(0, "", "暂无业绩可分")); 
			return;
		}else{
			allPrice = allPrice * 0.03; //拿出业绩的3%分红
		}
		
		List<Agents> agentList = Agents.dao.find("select * from Agents where canShare = 1 and reviewedState = " + ConstantUtils.StateAgentPass);
		int agentCount = agentList.size();
		for (int i = 0; i < agentCount; i++) {
			Agents agents = agentList.get(i);
			double moneyCount = MoneyUtils.formatDouble((double)allPrice/(double)agentCount);
			double endMoneyCount = moneyCount;
			if ((agents.getHadShareMoney()+moneyCount)>=agents.getAgentPrice()) {
				endMoneyCount = agents.getAgentPrice() - agents.getHadShareMoney();
				Agents.dao.findById(agents.getAgentId()).set("canShare", 0).set("hadShareMoney", agents.getAgentPrice()).update();
			}else{
				Agents.dao.findById(agents.getAgentId()).set("hadShareMoney", agents.getHadShareMoney()+endMoneyCount).update();
			}
			
			String desc = "公司第"+maxTime+"次业绩3%分红";
			
			double moneyCountAgent = MoneyUtils.formatDouble(endMoneyCount*0.97);
			new Moneyrecords().set("type", 3).set("moneyCount", moneyCountAgent).set("fromId", "0")
			.set("desc", desc).set("userOrAgentId", agents.getAgentId()).set("userType", 2).save();
			
			double moneyCount1 = MoneyUtils.formatDouble(endMoneyCount*0.01);
			String desc1 = desc+"的1%爱心基金";
			//审核通过后  需要记录一下 
        	addRecord(ConstantUtils.MonneyTypeAixin, moneyCount1, "0", desc1, agents.getAgentId());
        	
        	double moneyCount2 = MoneyUtils.formatDouble(endMoneyCount*0.02);
			String desc2 = desc+"的2%旅游基金";
			//审核通过后  需要记录一下 
        	addRecord(ConstantUtils.MonneyTypeLvYou, moneyCount2, "0", desc2, agents.getAgentId());
		}
		
		Db.update("UPDATE AgentOrders SET shareState = 1, shareTime = " + maxTime + " WHERE shareState = 0");
		Db.update("UPDATE Orders SET shareState = 1, shareTime = " + maxTime + " WHERE shareState = 0");
		renderText(ResponseUtils.sendResult(1, "", "分红成功  总共分红" + allPrice + "  获得分红人数"+agentCount)); 
	}
	
	//添加爱心基金   旅游基金  提现手续费记录
    private void addRecord(int type, double count, String fromId, String desc, int agentId) {
    	new Moneyrecords().set("type", type).set("moneyCount", count).set("fromId", fromId).set("desc", desc)
    	.set("userOrAgentId", agentId).set("userType", "2").save();
	}
	
	public void getList() {
		Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
		int agentParentId = loginAgents.getAgentId();
		int agentLevel = loginAgents.getAgentLevel();
		
		int pageNumber = getParaToInt("pageNumber")<1?1:getParaToInt("pageNumber");
		int pageSize = getParaToInt("pageSize")<1?1:getParaToInt("pageSize");
		int level = getParaToInt("level"); //代理等级
		
		String agentPhone = getPara("phone");
		String agentName = getPara("agentName");
		Page<Agents> list = null;
		
		int allAgentCount = 0;
		int allTopAgentCount = 0;
		int allFirstAgentCount = 0;
		int allSecondAgentCount = 0;
		int allVipCount = 0;
		
		if (agentLevel == ConstantUtils.LevelSuper) { //公司
			Record recordAllAgentCount = Db.findFirst("select count(*) as allAgentCount from Agents where agentId!="+ loginAgents.getAgentId());
			if (recordAllAgentCount.get("allAgentCount")!=null) {
				allAgentCount = recordAllAgentCount.getInt("allAgentCount");
			}
			
			Record recordAllTopAgentCount = Db.findFirst("select count(*) as allTopAgentCount from Agents where agentLevel=" + ConstantUtils.LevelTop);
			if (recordAllTopAgentCount.get("allTopAgentCount")!=null) {
				allTopAgentCount = recordAllTopAgentCount.getInt("allTopAgentCount");
			}
			
			Record recordAllFirstAgentCount = Db.findFirst("select count(*) as allFirstAgentCount from Agents where agentLevel=" + ConstantUtils.LevelFirst);
			if (recordAllFirstAgentCount.get("allFirstAgentCount")!=null) {
				allFirstAgentCount = recordAllFirstAgentCount.getInt("allFirstAgentCount");
			}
			
			Record recordAllSecondAgentCount = Db.findFirst("select count(*) as allSecondAgentCount from Agents where agentLevel=" + ConstantUtils.LevelSecond);
			if (recordAllSecondAgentCount.get("allSecondAgentCount")!=null) {
				allSecondAgentCount = recordAllSecondAgentCount.getInt("allSecondAgentCount");
			}
			
			Record recordAllVipCount = Db.findFirst("select count(*) as allVipCount from Agents where agentLevel=" + ConstantUtils.LevelThird);
			if (recordAllVipCount.get("allVipCount")!=null) {
				allVipCount = recordAllVipCount.getInt("allVipCount");
			}
		} else{
			Record recordAllAgentCount = Db.findFirst("select count(*) as allAgentCount from Agents where (agentParentId=" + loginAgents.getAgentId()
					+ " or agentSecondParentId=" + loginAgents.getAgentId() + ") and agentId!="+ loginAgents.getAgentId());
			if (recordAllAgentCount.get("allAgentCount")!=null) {
				allAgentCount = recordAllAgentCount.getInt("allAgentCount");
			}
			
			Record recordAllTopAgentCount = Db.findFirst("select count(*) as allTopAgentCount from Agents where agentLevel=" + ConstantUtils.LevelTop
					+ " and (agentParentId=" + loginAgents.getAgentId()+ " or agentSecondParentId=" + loginAgents.getAgentId() +")");
			if (recordAllTopAgentCount.get("allTopAgentCount")!=null) {
				allTopAgentCount = recordAllTopAgentCount.getInt("allTopAgentCount");
			}
			
			Record recordAllFirstAgentCount = Db.findFirst("select count(*) as allFirstAgentCount from Agents where agentLevel=" + ConstantUtils.LevelFirst
					+ " and (agentParentId=" + loginAgents.getAgentId()+ " or agentSecondParentId=" + loginAgents.getAgentId() +")");
			if (recordAllFirstAgentCount.get("allFirstAgentCount")!=null) {
				allFirstAgentCount = recordAllFirstAgentCount.getInt("allFirstAgentCount");
			}
			
			Record recordAllSecondAgentCount = Db.findFirst("select count(*) as allSecondAgentCount from Agents where agentLevel=" + ConstantUtils.LevelSecond
					+ " and (agentParentId=" + loginAgents.getAgentId()+ " or agentSecondParentId=" + loginAgents.getAgentId() +")");
			if (recordAllSecondAgentCount.get("allSecondAgentCount")!=null) {
				allSecondAgentCount = recordAllSecondAgentCount.getInt("allSecondAgentCount");
			}
			
			Record recordAllVipCount = Db.findFirst("select count(*) as allVipCount from Agents where agentLevel=" + ConstantUtils.LevelThird
					+ " and (agentParentId=" + loginAgents.getAgentId()+ " or agentSecondParentId=" + loginAgents.getAgentId() +")");
			if (recordAllVipCount.get("allVipCount")!=null) {
				allVipCount = recordAllVipCount.getInt("allVipCount");
			}
		}
		
		String agentShareType = getPara("agentShareType");
		
		if (level==-1) { //登陆代理商推荐的全部代理商
			if (agentLevel == ConstantUtils.LevelSuper) { //公司
				if (StrUtils.isEmpty(agentShareType)) {
					list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
							"from Agents AgentsSource INNER JOIN Agents AgentParent "
							+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
									agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' order by AgentsSource.updatedAt desc");
				}else{
					list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
							"from Agents AgentsSource INNER JOIN Agents AgentParent "
							+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
									agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' and AgentsSource.canShare = ? order by AgentsSource.updatedAt desc", agentShareType);
				}
			} else{
				if (StrUtils.isEmpty(agentShareType)) {
					list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
						"from Agents AgentsSource INNER JOIN Agents AgentParent "
						+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
						agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' and (AgentsSource.agentId = ? or AgentsSource.agentParentId = ? or AgentsSource.agentSecondParentId = ?) "
						+ "order by AgentsSource.updatedAt desc", agentParentId, agentParentId, agentParentId);
				}else{
					list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
							"from Agents AgentsSource INNER JOIN Agents AgentParent "
							+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
							agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' and (AgentsSource.agentId = ? or AgentsSource.agentParentId = ? or AgentsSource.agentSecondParentId = ?) "
							+ " and AgentsSource.canShare = ? order by AgentsSource.updatedAt desc", agentParentId, agentParentId, agentParentId, agentShareType);
				}
			}
		}else{ //直推代理商
			if (agentLevel == ConstantUtils.LevelSuper) { //公司 
				if (StrUtils.isEmpty(agentShareType)) {
					list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
						"from Agents AgentsSource INNER JOIN Agents AgentParent "
						+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
						agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' and AgentsSource.agentLevel = ?  order by AgentsSource.updatedAt desc", level);
				}else{
					list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
							"from Agents AgentsSource INNER JOIN Agents AgentParent "
							+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
							agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' and AgentsSource.agentLevel = ? and AgentsSource.canShare = ?  order by AgentsSource.updatedAt desc", level, agentShareType);
				}
				
			} else{ 
				list = Agents.dao.paginate(pageNumber, pageSize, "select AgentsSource.*, AgentParent.agentName as parentAgentName ",
						"from Agents AgentsSource INNER JOIN Agents AgentParent "
						+ "ON AgentParent.agentId = AgentsSource.agentParentId where AgentsSource.agentPhone like '%" + 
						agentPhone+"%' and AgentsSource.agentMan like '%" + 
									agentName+"%' and (AgentsSource.agentId = ? or AgentsSource.agentParentId = ? or AgentsSource.agentSecondParentId = ?) "
						+ " and AgentsSource.agentLevel = ?  order by AgentsSource.updatedAt desc", 
						agentParentId, agentParentId, agentParentId, level);
			}
			
		}
		 
		JSONObject object = new JSONObject();
		object.put("allAgentCount", allAgentCount);
		object.put("allTopAgentCount", allTopAgentCount);
		object.put("allFirstAgentCount", allFirstAgentCount);
		object.put("allSecondAgentCount", allSecondAgentCount);
		object.put("allVipCount", allVipCount);
		object.put("listData", list); 
		
        renderText(ResponseUtils.sendResult(1, object, "获取数据成功"));
    }
	
	/**  
	 * 添加
     */  
    public void addAgents() {
    	Agents agents = new Agents();
    	agents.setAgentNO(getPara("agentNO"));
    	agents.setAgentLevel(getParaToInt("agentLevel"));
    	agents.setAgentUpdateLevel(getParaToInt("agentLevel"));
        agents.setAdress(getPara("adress"));
        agents.setArea(getPara("area"));
        agents.setCity(getPara("city"));
        agents.setProvince(getPara("province"));
//      agents.setAgentName(getPara("agentName")); 代理商名称  联系人  暂时不添加这两个  用真实姓名代替 
//        agents.setAgentMan(getPara("agentMan"));
        agents.setAgentMan(getPara("realName"));
        agents.setAgentName(getPara("realName"));
        agents.setAgentPhone(getPara("agentPhone"));
        agents.setAgentPassword(getPara("agentPassword"));
        int canShare = getParaToInt("canShare");
        agents.setCanShare(canShare);
        agents.setAgentParentId(getParaToInt("agentParentId"));
        agents.setRealName(getPara("realName"));
        agents.setBankCardNumber(getPara("bankCardNumber"));
        agents.setBankName(getPara("bankName"));
        agents.setIdCardNO(getPara("idCardNO"));
        agents.setAgentPrice(0);
        agents.setReviewedState(ConstantUtils.StateAgentWaitReView);
    	
        if (agents.getAgentNO()==null) {
    		renderText(ResponseUtils.sendResult(0, "", "必须填写推荐代理商编号")); 
    		return;
		}
    	
    	Agents parentAgents = Agents.dao.findFirst("select * from agents where agentNO = ?", agents.getAgentNO());
    	if (parentAgents==null) {
    		renderText(ResponseUtils.sendResult(0, "", "找不到推荐代理商，请检查推荐代理商编号")); 
    		return;
		}
    	agents.setAgentParentId(parentAgents.getAgentId());
    	
    	if (StrUtils.isEmpty(agents.getAgentPhone())) {
    		renderText(ResponseUtils.sendResult(0, "", "必须填写代理商手机号码")); 
    		return;
		}else{
			Agents agentPhoneAgents = Agents.dao.findFirst("select * from agents where agentPhone = ?", agents.getAgentPhone());
			if (agentPhoneAgents!=null) {
				renderText(ResponseUtils.sendResult(0, "", "该代理商手机号码已存在")); 
	    		return;
			}
		}
    	
    	String orderDatas = getPara("orderDatas");
    	int payType = getParaToInt("payType");
    	Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
    	if (loginAgents.getAgentLevel()==ConstantUtils.LevelSuper) { //公司不用审核，直接添加
    		agents.setReviewedState(ConstantUtils.StateAgentPass);
    		int agentPrice = getParaToInt("agentPrice");
    		agents.setAgentPrice(agentPrice);
    		//检查代理商总进货款  如果满50万才可设置为可分红
    		if (canShare==1 && agentPrice<ConstantUtils.LevelTopMoney) { //不满50万   不可设置为可分红
    			renderText(ResponseUtils.sendResult(0, "", "代理商进货款不足50万，不可设置为有权分红")); 
        		return;
			}else if (agentPrice>=ConstantUtils.LevelTopMoney){
				agents.setAgentPrice(ConstantUtils.LevelTopMoney); //可分红金额最多50万
			}
		}else{
            if (StrUtils.isEmpty(orderDatas) || orderDatas.length()<10 ) {
            	renderText(ResponseUtils.sendResult(0, "", "订单信息不能为空")); 
        		return;
    		}
            String payImg = getPara("payImg");
        	if (StrUtils.isEmpty(payImg) && payType!=ConstantUtils.TypePayCash) {
            	renderText(ResponseUtils.sendResult(0, "", "非现金支付方式支付截图不能为空")); 
        		return;
    		}
		}
    	
    	int agentSecondParentId = 0;
		agentSecondParentId = parentAgents.getAgentParentId();
    	
    	Record recordMax = Db.findFirst("select max(agentId) as maxAgentId from agents");
		int maxAgentId = 0;
		if (recordMax.get("maxAgentId")!=null) {
			maxAgentId = recordMax.getInt("maxAgentId") + 1;
		}
    	agents.setAgentNO("CH"+maxAgentId);
    	agents.setAgentSecondParentId(agentSecondParentId);
        boolean flag = agents.save();
        if (flag) {  
        	Agents agentPhoneAgents = Agents.dao.findFirst("select * from agents where agentPhone = ?", agents.getAgentPhone());
        	if (!StrUtils.isEmpty(orderDatas) && orderDatas.length()>10 ) {
	        	Agentorders agentOrders = new Agentorders();
	        	agentOrders.setAddressDetail(agents.getAdress());
	        	agentOrders.setProvince(agents.getProvince());
	        	agentOrders.setArea(agents.getArea());
	        	agentOrders.setCity(agents.getCity());
	        	agentOrders.setAgentOrderId(UUidUtils.getUUid());
	        	agentOrders.setBuyAgentId(agentPhoneAgents.getAgentId());
	        	if (loginAgents.getAgentLevel()==ConstantUtils.LevelSuper) { //公司不用审核，直接通过
	        		agentOrders.setState(ConstantUtils.StateOrderPass);
	        	}else{
	        		agentOrders.setState(ConstantUtils.StateOrderHadPay);
	        	}
	        	agentOrders.setMan(agents.getAgentMan());
	        	agentOrders.setPhone(agents.getAgentPhone());
	        	agentOrders.setGoodDatas(orderDatas);
	        	agentOrders.setPayType(payType);
	        	agentOrders.setPayImg(getPara("payImg"));
	        	agentOrders.setOrderType(ConstantUtils.TypeAgentOrderAdd);
	        	agentOrders.setPrice(Double.parseDouble(getPara("agentPrice")));
	        	while (parentAgents.getAgentLevel()>ConstantUtils.LevelTop && parentAgents.getAgentLevel()>=agents.getAgentLevel()){
	        		//如果父代理不为总代理或者公司  而且父代理级别不比新加代理高  则寻找到总代理后者公司为止
	            	parentAgents = Agents.dao.findFirst("select * from agents where agentId = ?", parentAgents.getAgentParentId());
	        	}
	        	agentOrders.setSaleAgentId(parentAgents.getAgentId());
	        	if (parentAgents.getAgentLevel()==ConstantUtils.LevelSuper) {
	        		agentOrders.setSaleAgentId(ConstantUtils.SuperAgentId);
	        		agentOrders.setShareState(0); //算入公司营业额的订单  0可分红但是未分红  1已分红  2不可分红  只有公司创始代理销货订单才可算入分红
				}else{
					agentOrders.setShareState(3); //算入公司营业额的订单  0可分红但是未分红  1已分红  2不可分红  只有公司创始代理销货订单才可算入分红
				}
	        	agentOrders.save();
        	}
        	
        	Admins admins = new Admins();
        	admins.setAdminName(agents.getAgentName());
        	admins.setAdminPhone(agents.getAgentPhone());
        	admins.setAdminPassword(agents.getAgentPassword());
        	admins.setAgentId(agentPhoneAgents.getAgentId());
        	admins.save();
        	renderText(ResponseUtils.sendResult(1, "", "添加成功")); 
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "添加失败"));  
        }  
    }

    /** 
     * 修改 代理商信息
     */   
    public void changeAgentsInfo() {   
    	if (StrUtils.isEmpty(getPara("agentId"))) {
    		renderText(ResponseUtils.sendResult(0, "", "找不到要更新的代理商")); 
    		return;
		}
    	Agents agents = new Agents();
    	agents.setAgentId(getParaToInt("agentId"));
        agents.setAdress(getPara("adress"));
        agents.setArea(getPara("area"));
        agents.setCity(getPara("city"));
        agents.setProvince(getPara("province"));
        // 代理商名称  联系人  暂时不添加这两个  用真实姓名代替 
        agents.setAgentMan(getPara("realName"));
        agents.setAgentName(getPara("realName"));
        agents.setAgentPhone(getPara("agentPhone"));
        int canShare = getParaToInt("canShare");
        agents.setCanShare(canShare);
        agents.setRealName(getPara("realName"));
        agents.setBankCardNumber(getPara("bankCardNumber"));
        agents.setBankName(getPara("bankName"));
        agents.setIdCardNO(getPara("idCardNO"));
    	
    	Agents loginAgents = getAttr("loginAgents");
    	if (loginAgents.getAgentLevel()!=ConstantUtils.LevelSuper) {
    		renderText(ResponseUtils.sendResult(0, "", "只有公司管理员才能修改代理商信息")); 
    		return;
		}
    	
    	if (canShare==1) {
    		ArrayList<Agentorders> listAgentBuyOrders = (ArrayList<Agentorders>) Agentorders.dao.find("select * from AgentOrders where buyAgentId = "
        			+ getPara("agentId") + " and (state = " + ConstantUtils.StateOrderPass +
        			" or state = " + ConstantUtils.StateOrderSendGood + " or state = " + ConstantUtils.StateOrderTakeGood + ")");
        	double allBuyPrice = 0;
        	for (int i = 0; i < listAgentBuyOrders.size(); i++) {
        		Agentorders agentorders = listAgentBuyOrders.get(i);
        		allBuyPrice = allBuyPrice + agentorders.getPrice();
			}
        	if (allBuyPrice<ConstantUtils.LevelTopMoney) {
        		renderText(ResponseUtils.sendResult(0, "", "只有累计进货满50万才可有权分红")); 
        		return;
			}
		}
    	
    	agents.setUpdatedAt(new Date());
        boolean flag = agents.update();
        if (flag) {  
        	renderText(ResponseUtils.sendResult(1, "", "修改成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "修改失败"));  
        }   
    }  
    
    /** 
     * 重置代理商登陆密码
     */   
    public void resetAgentsPwd() {  
    	Admins loginAdmins = getAttr("loginAdmins");
    	Agents loginAgents = getAttr("loginAgents");
    	if (loginAgents.getAgentLevel()!=ConstantUtils.LevelSuper  && loginAdmins.getType()==ConstantUtils.TypeAdminSuper) {
    		renderText(ResponseUtils.sendResult(0, "", "只有公司全权管理员才能修改代理商信息")); 
    		return;
		}
    	String agentId = getPara("agentId");
    	String secPassword = getPara("secPassword");
    	String loginSecPassword = loginAgents.getSecPassword();
    	if (!loginSecPassword.equals(secPassword)) {
    		renderText(ResponseUtils.sendResult(0, "", "二次密码不正确")); 
    		return;
		}
    	Agents agents = Agents.dao.findById(agentId);
    	Admins admins = Admins.dao.findFirst("select * from Admins where adminPhone = \'" + agents.getAgentPhone() +"\'" );
    	admins.setAdminPassword("fcea920f7412b5da7be0cf42b8c93759");  //默认密码1234567
    	admins.setUpdatedAt(new Date());
        boolean flag = admins.update();
        if (flag) {  
        	renderText(ResponseUtils.sendResult(1, "", "修改成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "修改失败"));  
        }   
    }
      
    /***
     * 升级代理商信息
     */
    public void updateAgentsLevel() {  
    	int agentLevel = getParaToInt("agentLevel");
    	String agentId = getPara("agentId");
    	
//    	Agents loginAgents = getAttr("loginAgents");
//    	if (loginAgents.getAgentLevel()!=ConstantUtils.LevelSuper) {
//    		renderText(ResponseUtils.sendResult(0, "", "只有公司管理员才能升级代理商")); 
//    		return;
//		}
    	
    	Agents agents = Agents.dao.findFirst("select * from agents where agentId = ?", agentId);
    	if (agents==null) {
    		renderText(ResponseUtils.sendResult(0, "", "找不到需要升级的代理商")); 
    		return;
		}
    	
    	if (agents.getReviewedState()==ConstantUtils.StateAgentWaitReView) {
    		renderText(ResponseUtils.sendResult(0, "", "待审核状态的代理商无法升级")); 
    		return;
		}
    	
    	if (agentLevel==ConstantUtils.LevelTop) { //总代理需要先推荐三个代理
    		int agentCount = 0; 
    		Record recordAgentCount = Db.findFirst("select count(*) as agentCount from Agents where agentParentId=" + agentId + " and agentLevel <" 
    					+ ConstantUtils.LevelThird);
			if (recordAgentCount.get("agentCount")!=null) {
				agentCount = recordAgentCount.getInt("agentCount");
			}
			if (agentCount<3) {
				renderText(ResponseUtils.sendResult(0, "", "总代理必须要推荐3个代理才可升级")); 
	    		return;
			}
		}
    	
    	String orderDatas = getPara("orderDatas");
    	if (orderDatas.length()<10) { //说明有进货
    		renderText(ResponseUtils.sendResult(0, "", "升级必须进货")); 
    		return;
    	}
    	
    	int payType = getParaToInt("payType");
        String payImg = getPara("payImg");
    	if (StrUtils.isEmpty(payImg) && payType!=ConstantUtils.TypePayCash) {
        	renderText(ResponseUtils.sendResult(0, "", "非现金支付方式支付截图不能为空")); 
    		return;
		}
    	
    	int price = getParaToInt("agentPrice");
    	if (agentLevel==ConstantUtils.LevelTop && price<ConstantUtils.LevelTopMoney) {
    		renderText(ResponseUtils.sendResult(0, "", "总代理升级必须进货"+ConstantUtils.LevelTopMoney+"元")); 
    		return;
    	}
    	if (agentLevel==ConstantUtils.LevelFirst && price<ConstantUtils.LevelFirstMoney) {
    		renderText(ResponseUtils.sendResult(0, "", "一级代理升级必须进货"+ConstantUtils.LevelFirstMoney+"元")); 
    		return;
    	}
    	if (agentLevel==ConstantUtils.LevelSecond && price<ConstantUtils.LevelSecondMoney) {
    		renderText(ResponseUtils.sendResult(0, "", "二级代理升级必须进货"+ConstantUtils.LevelSecondMoney+"元")); 
    		return;
    	}
    	
    	if (agentLevel>=agents.getAgentLevel()) {
    		renderText(ResponseUtils.sendResult(0, "", "等级必须更高才能升级")); 
    		return;
		}
    	
    	Agents parentAgents = Agents.dao.findFirst("select * from agents where agentId = ?", getPara("agentParentId"));
//    	agents.setAgentPrice(price); 只有审核通过  这个才能变
    	agents.setAgentUpdateLevel(agentLevel);
    	agents.setUpdatedAt(new Date());
    	agents.setReviewedState(ConstantUtils.StateAgentWaitReView);
        boolean flag = agents.update();
        if (flag) {  
        	if (orderDatas.length()>10) { //说明有进货
	        	Agentorders agentOrders = new Agentorders();
	        	agentOrders.setAddressDetail(agents.getAdress());
	        	agentOrders.setProvince(agents.getProvince());
	        	agentOrders.setArea(agents.getArea());
	        	agentOrders.setCity(agents.getCity());
	        	agentOrders.setAgentOrderId(UUidUtils.getUUid());
	        	agentOrders.setBuyAgentId(agents.getAgentId());
	        	agentOrders.setState(ConstantUtils.StateOrderHadPay);
	        	agentOrders.setMan(agents.getAgentMan());
	        	agentOrders.setPhone(agents.getAgentPhone());
	        	agentOrders.setGoodDatas(orderDatas);
	        	agentOrders.setPayImg(getPara("payImg"));
	        	agentOrders.setPayType(payType);
	        	agentOrders.setOrderType(ConstantUtils.TypeAgentOrderUpdateLevel);
	        	agentOrders.setPrice((double)price); 
	        	while (parentAgents.getAgentLevel()>=agents.getAgentUpdateLevel()){
	        		//如果父代理不为总代理或者公司  而且父代理级别不比新加代理高  则寻找到总代理后者公司为止
	            	parentAgents = Agents.dao.findFirst("select * from agents where agentId = ?", parentAgents.getAgentParentId());
	        	}
	        	agentOrders.setSaleAgentId(parentAgents.getAgentId());
	        	if (parentAgents.getAgentLevel()==ConstantUtils.LevelSuper) {
	        		agentOrders.setSaleAgentId(ConstantUtils.SuperAgentId);
	        		agentOrders.setShareState(0); //算入公司营业额的订单  0可分红但是未分红  1已分红  2不可分红  只有公司创始代理销货订单才可算入分红
				}else{
					agentOrders.setShareState(3); //算入公司营业额的订单  0可分红但是未分红  1已分红  2不可分红  只有公司创始代理销货订单才可算入分红
				}
	        	agentOrders.save();
        	}
        	renderText(ResponseUtils.sendResult(1, "", "修改成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "修改失败"));  
        }   
    }  
    
    /** 
     * 删除单个 
     */  
    public void delAgentsById() {  
        Integer id = getParaToInt("agentId");  
        boolean flag = Agents.dao.deleteById(id);  
        if (flag) {  
        	renderText(ResponseUtils.sendResult(1, "", "删除成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "删除失败"));  
        }    
    } 
	
}
